package com.mycompany.repository.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import com.mycompany.entity.Number;
import com.mycompany.repository.NumberDao;

@Repository
public class NumberDaoImpl implements NumberDao {
	
	private EntityManager em;
	String sqlQuery="";
	

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.em = entityManager;
	}

	@Override
	public void persist(Number number) {
		em.persist(number);
	}

	@Override
	public void merge(Number number) {
		em.merge(number);
	}

	@Override
	public void remove(Number number) {
		number.setActiveFlg(false);
		em.merge(number);
	}

	@Override
	public Number findById(Integer numberId) {
		sqlQuery = "select x from Number x where x.numberId= :numberId and x.activeFlg = 1";
		return (Number) em.createQuery(sqlQuery).setParameter("numberId", numberId).getSingleResult();
	}

	@Override
	public Number find(Number number) {
		sqlQuery = "select x from Number x where x.numberId= :numberId and x.activeFlg = 1";
		return (Number) em.createQuery(sqlQuery).setParameter("numberId", number.getNumberId()).getSingleResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Number> findAll() {
		sqlQuery = "select x from Number x where x.activeFlg = 1 and activeFlg = '1' ORDER BY x.numberId DESC ";
        return em.createQuery(sqlQuery).getResultList();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Number> findAllTop10() {
		sqlQuery = "select x from Number x where x.activeFlg = 1 ORDER BY x.numberId DESC";
        return em.createQuery(sqlQuery)
        		.setFirstResult(0)
                .setMaxResults(10)
                .getResultList();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Number> findListByCodition(Number number) {
		sqlQuery = "select * from number where 1=1 ";
		if(!number.getNumber().isEmpty()){
			sqlQuery = sqlQuery+" AND number = '"+number.getNumber()+"' ";
		}
		if(!number.getType().isEmpty()){
			sqlQuery = sqlQuery+" AND type = '"+number.getType()+"' ";
		}
		
		sqlQuery = sqlQuery+ " and activeFlg = '1' ORDER BY numberId DESC "; 
        return em.createNativeQuery(sqlQuery,Number.class).getResultList();
	}
}
